import React, { Component } from 'react'
import { withRouter } from "react-router-dom"
import styles from "../Login/Login.module.scss"
import {  getCaptchas,} from "../../http/api"
import x from "../../images/x.jpg"
import axios from 'axios'
import store from "../../redux/store/index"
import { initUserInfoAction } from "../../redux/actionCreators/Login_action"
import { connect } from "react-redux"
class Demo extends Component {
  render() {
    return <h1>{this.props.token}</h1>
  }
}
let ConnectDemo = connect((state) => {
  return {
    token: state.loginReducer.wdata&& state.loginReducer.wdata.oauth_token || ""
  }
}, null)(Demo)

class Login extends Component {
  // componentDidMount(){
  //   console.log(this.props.token);

  //   if(!this.props.token){
  //     if(localStorage.getItem("token")){
  //       this.state.token = localStorage.getItem("token");
  //       console.log(this);
  //     }else{
  //      console.log("登陆过期,请从新登陆");
  //       this.props.push("login")
  //     }
  //   }
  // }
  state = {
    mobile: "18988938574",//手机号
    password: "",//密码
    isLogin: false,//是否登录
    phoneCode: '',
    captcha_code: "",//密码验证码
    checked: false,//服务条款的选中状态
    timeId: 60,
    id: '',
    isLogin: false,//登录状态
    msg_code: "",//验证码为
    msg_pass: "",//验证密码
    error_msg: "",//验证手机号
    codeClick: true,//验证倒计时
    code: "",//验证码图片
    loginActive: true,//切换密码验证码
  };

  timeLose = () => {
    let that = this;
    setInterval(() => {
      that.setState((preState) => {
        return {
          timeId: --preState.timeId,
        }
      });
    }, 1000)
  };

  timeExist = () => {
    setTimeout(() => {
      this.setState({
        codeClick: true,
      });
    }, 60000);
  };

  handleDel = (params) => {

    this.props.history.push("/cart");
    localStorage.removeItem("token");

  };
  handleCodeChange = (e) => {
    this.setState({
      phoneCode: e.target.value,
    })
  }
  handleChange = (e) => {
    let { type, key } = e.target.dataset;
    let value = "";
    if (type === "checkbox") {
      value = e.target.checked;
    } else {
      value = e.target.value;
    }
    this.setState({
      [key]: value,
    })
  };

  handleChangeActive = () => {
    if (this.state.loginActive === true) {
      this.setState({
        loginActive: false,
      })
    } else {
      this.setState({
        loginActive: true,
      })
    }
  };

 handleAGetCode = async () => {
  let res = await getCaptchas(this.state.code);
  console.log(res);
  this.setState({
    codeClick: false,
    code: res.code,
  });

    this.timeLose();
    this.timeExist();
  };

  handleLogin = async () => {
    console.log("手机号为:", this.state.mobile);
    let mobile = this.state.mobile;
    let valid = this.validateMobile(mobile);
    if (!valid) {
      return false;
    };
    console.log("密码为:", this.state.password);
    let password = this.state.password;
    let valit = this.valitataPassword(password);
    if (!valit) {
      return false;
    }

    // let phoneCode = this.state.phoneCode;
    // console.log("验证码为:", phoneCode);
    // let res = await getLogin(
    //   this.state.mobile,
    //   this.state.password,
    //   this.state.phoneCode);
    // if (!res === 0) {
    //   this.props.history.push("cart");
    //   this.setState({
    //     isLogin: true,
    //   })
    // }

    axios.post("http://s.linweiqin.com/api/s/loginCheck", {
      username: this.state.mobile,
      password: this.state.password,
    }).then(res => {
      let token =res.data.wdata.oauth_token;
      console.log(token);
       // 儲存token到local
      localStorage.setItem("token", token);
     
      if (token) {
        this.props.history.push("home");
        console.log(res.data);
      } else {
       
      }
      store.dispatch(initUserInfoAction(res.data.wdata));
    });
  };
  // handleDelT =() => {
  //   let token =res.data.wdata.oauth_token;
  //   localStorage.removeItem(token);
  // }
  validateMobile = (mobile) => {
    // 手机号码不能为空
    if (!mobile) {
      this.setState({
        error_msg: "手机号码不能为空",
      })
      return false
    }
    if (!/^1[0-9]{10}$/.test(mobile)) {
      this.setState({
        error_msg: "手机格式输入有误,请重新输入",
      })
      return false
    }
    return true;
  };

  valitataPassword = (password) => {
    if (!password) {
      this.setState({
        msg_pass: '密码不能为空',
      })
      return false
    }
    if (!/^\d{6,12}$/) {//!/^(?![a-zA-Z]+$)(?![0-9]+$)[A-Za-z0-9]{6,12}$/
      this.setState({
        msg_pass: "密码必须包括(6-12位)数字，"
      })
      return false
    }
    return true
  };


  render() {
    return (
      <div className={styles.login}>
        {/* 头部标题开始 */}

        <div className={styles.loginHeader}>
          <div className={styles.loginHeaderTitle}>欢迎登录/注册</div>
          <div className={styles.loginHeaderDel} onClick={this.handleDel} > X</div>
        </div>
        {/* 头部标题结束 */}
        {/* 登录头像 开始*/}
        <div className={styles.loginImg}>
          <img src={x} alt="" />
        </div>
        {/* 登录头像结束 */}
        {/* 输入手机号 */}
        <div className={styles.loginUsername}>
          <span>+86 <a href="#">{">"}</a></span>
          <input type="text"
            data-key="mobile"
            data-type="text"
            value={this.state.mobile}
            id={styles.username}
            onChange={this.handleChange}
            placeholder="请输入手机号" />
        </div>

        {/* 输入密码/验证码 */}
        {
          // 密码输入
          this.state.loginActive ? (
            <div>
              <div className={styles.loginPassword}>
                <input type="password"
                  id={styles.password}
                  data-key="password"
                  data-type="text"
                  value={this.state.password}
                  onChange={this.handleChange}
                  placeholder="请输入密码" />
              </div>
              <div className={styles.loginPhonePassword}>
                <input type="string"
                  data-key="phoneCode"
                  data-type="text"
                  placeholder="请输入短信验证码"
                  value={this.state.phoneCode}
                  onChange={this.handleCodeChange}
                />
                {
                  this.state.codeClick ? (
                    <div className={styles.loginPhoneCode}
                      onClick={this.handleAGetCode}>
                      发送验证码
                    </div>
                  ) : (
                    <div className={styles.wait60s}>
                      {this.state.timeId}秒后重发
                    </div>
                  )}
              </div>
              <img src={this.state.code} alt="" />

              {
                this.state.error_msg ? <span className={styles.error}> {this.state.error_msg}</span> : ""
              }
              {
                this.state.msg_pass ? <span className={styles.error}>{this.state.msg_pass}</span> : ""
              }
              {/* //18988938574 */}
              <div className={styles.loginBtn} onClick={this.handleLogin}>
                登录
               </div>
              {/* <button onClick={() => {
                console.log(store.getState())
              }}>获取仓库中的值</button> */}
             
              <div className={styles.title}>
                <div>
                  温馨提示:未注册过的账号，登录时将自动注册
                </div>
                <div>
                  注册过的用户可凭账号密码登录
                 </div>
              </div>
              <div className={styles.loginVerify}>
                <div className={styles.loginCheck}
                  onClick={this.handleChangeActive}>手机短信登录/注册</div>
                <div>遇到问题</div>
              </div>

              <div className={styles.loginPolicy}>
                <input type="checkbox" name="" id=""
                  checked={this.state.checked}
                  data-key="checked"
                  data-type="checkbox"
                  onChange={this.handleChange} />
                <span>我同意{"<<"} <a>服务条款</a> {">>"}和{"<<"}<a>隐私政策</a>{">>"}</span>
              </div>
            </div>
          ) : (
            <div>
              {/* 验证码输入 */}
              <div className={styles.loginPhonePassword}>
                <input type="number"
                  placeholder="请输入短信验证码"
                  data-key="msg_code"
                  data-type="number"
                  value={this.state.msg_code}
                  onChange={this.handleChange}
                />
                {
                  this.state.codeClick ? (
                    <div className={styles.loginPhoneCode}
                      onClick={this.handleAGetCode}>
                      发送验证码
                    </div>
                  ) : (
                    <div className={styles.wait60s}>
                      {this.state.timeId}秒后重发
                    </div>
                  )}
              </div>
              <img src={this.state.code} alt="" />
              {
                this.state.error_msg ? <span className={styles.error} style={{ color: "red" }}>{this.state.error_msg}</span> : ""
              }
              {
                this.state.msg_pass ? <span className={styles.error}>{this.state.msg_pass}</span> : ""
              }
              <div className={styles.loginBtn} onClick={this.handleLogin}>
                立即登录/注册
               </div>

              <div className={styles.loginVerify}>
                <div className={styles.loginCheck} onClick={this.handleChangeActive}>用户名密码登录</div>
                <div>遇到问题</div>
              </div>

              <div className={styles.loginPolicy}>
                <input type="checkbox" name="" id=""
                  checked={this.state.checked}
                  data-key="checked"
                  data-type="checkbox"
                  onChange={this.handleChange} />
                <span>我同意{"<<"} <a>服务条款</a> {">>"}和{"<<"}<a>隐私政策</a>{">>"}</span>
              </div>
            </div>
          )}
      </div>
    );
  }
}
export default withRouter(Login);